package com.hhss.qishi.utils;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hhss
 * @date 2019年4月20日
 */
public class VerfiyCodeUtil {

    /**
     * 校对验证码，默认验证码的入参名称为tryCode
     * @param httpServletRequest
     * @return
     */
    public static boolean verify(HttpServletRequest httpServletRequest) {
        boolean isPass = false;
        String rightCode = (String) httpServletRequest.getSession().getAttribute("rightCode");
        String tryCode = httpServletRequest.getParameter("tryCode");
        if (StringUtils.isEmpty(rightCode)) {
            isPass = false;
        } else if (rightCode.equals(tryCode)) {
            isPass = true;
            // 清空验证码
            httpServletRequest.getSession().setAttribute("rightCode", null);
        }
        return isPass;
    }

    /**
     * 校对验证码，制定验证码的入参名称
     * @param httpServletRequest
     * @param codeName
     * @return
     */
    public static boolean verify(HttpServletRequest httpServletRequest, String codeName) {
        if (StringUtils.isEmpty(codeName)) {
           return verify(httpServletRequest);
        } else {
            boolean isPass = false;
            String rightCode = (String) httpServletRequest.getSession().getAttribute("rightCode");
            String tryCode = httpServletRequest.getParameter(codeName);
            if (StringUtils.isEmpty(rightCode)) {
                isPass = false;
            } else if (rightCode.equals(tryCode)) {
                isPass = true;
                // 清空验证码
                httpServletRequest.getSession().setAttribute("rightCode", null);
            }
            return isPass;
        }
    }
}
